#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
处理流速数据分析脚本
在processed文件夹中查找500f*ms或1000f*ms文件夹，提取CSV文件中的最大值
"""

import os
import pandas as pd
import re

def extract_flow_rate(folder_name):
    """从文件夹名中提取流速值"""
    # 匹配500f或1000f开头的文件夹
    match = re.search(r'(500f|1000f)([\d.-]+)ms', folder_name)
    if match:
        flow_str = match.group(2)
        try:
            return float(flow_str)
        except ValueError:
            return None
    return None

def find_csv_files(directory: str) -> dict[str, str | None]:
    """在目录中查找CSV文件"""
    csv_files: dict[str, str | None] = {'deviation': None, 'displacement': None}
    
    for root, dirs, files in os.walk(directory):
        for file in files:
            if file == 'deviation_from_center_data.csv':
                csv_files['deviation'] = os.path.join(root, file)
                print(f"  - 找到偏差数据文件: {csv_files['deviation']}")
            elif file == 'displacement_data.csv':
                csv_files['displacement'] = os.path.join(root, file)
                print(f"  - 找到位移数据文件: {csv_files['displacement']}")
    
    return csv_files

def get_max_values_from_csv(csv_path):
    """获取CSV文件第2、3列的最大值（跳过表头）"""
    print(f"  - 正在从文件 '{os.path.basename(csv_path)}' 提取最大值...")
    try:
        # 读取CSV文件，跳过第一行表头
        df = pd.read_csv(csv_path, skiprows=1, header=None)
        if len(df.columns) >= 3:
            # 将数据转换为数值类型，非数值变为NaN
            col2 = pd.to_numeric(df.iloc[:, 1], errors='coerce')
            col3 = pd.to_numeric(df.iloc[:, 2], errors='coerce')
            
            # 删除NaN值
            col2 = col2.dropna()
            col3 = col3.dropna()
            
            if len(col2) > 0 and len(col3) > 0:
                max_col2 = col2.max()
                max_col3 = col3.max()
                print(f"    - 提取到最大值: 第2列={max_col2}, 第3列={max_col3}")
                return max_col2, max_col3
    except Exception as e:
        print(f"读取文件 {csv_path} 时出错: {e}")
    print(f"    - 未能从文件 '{os.path.basename(csv_path)}' 提取到有效最大值。")
    return None, None

def process_processed_folder(processed_folder):
    """处理单个processed文件夹"""
    results = []
    
    # 查找所有500f*ms或1000f*ms文件夹
    flow_folders = []
    for item in os.listdir(processed_folder):
        item_path = os.path.join(processed_folder, item)
        if os.path.isdir(item_path) and (item.startswith('500f') or item.startswith('1000f')) and item.endswith('ms'):
            flow_folders.append(item)
    
    print(f"在 {os.path.basename(processed_folder)} 中找到 {len(flow_folders)} 个流速文件夹")
    
    for flow_folder in flow_folders:
        flow_path = os.path.join(processed_folder, flow_folder)
        flow_rate = extract_flow_rate(flow_folder)
        
        print(f"  - 正在处理流速文件夹: {flow_folder}, 提取流速: {flow_rate if flow_rate is not None else 'N/A'}")
        
        if flow_rate is None:
            print(f"    - 无法从文件夹名 '{flow_folder}' 提取流速，跳过。")
            continue
            
        # 查找CSV文件
        csv_files = find_csv_files(flow_path)
        
        # 获取数据
        dev_max2, dev_max3 = None, None
        if csv_files['deviation']:
            dev_max2, dev_max3 = get_max_values_from_csv(csv_files['deviation'])
        
        disp_max2, disp_max3 = None, None
        if csv_files['displacement']:
            disp_max2, disp_max3 = get_max_values_from_csv(csv_files['displacement'])
        
        # 只有当至少有一个有效值时才添加结果
        if any(v is not None for v in [dev_max2, dev_max3, disp_max2, disp_max3]):
            results.append({
                'flow_rate': flow_rate,
                'dev_max_col2': dev_max2,
                'dev_max_col3': dev_max3,
                'disp_max_col2': disp_max2,
                'disp_max_col3': disp_max3
            })
    
    return results

def main():
    """主函数"""
    base_path = r"J:\lqb\chongzuo\25CHJ02"
    
    if not os.path.exists(base_path):
        print(f"路径不存在: {base_path}")
        return
    
    # 查找所有processed文件夹
    processed_folders = []
    for item in os.listdir(base_path):
        item_path = os.path.join(base_path, item)
        if os.path.isdir(item_path) and item.endswith('_processed'):
            processed_folders.append(item_path)
            print(f"找到processed文件夹: {item_path}")
    
    print(f"总共找到 {len(processed_folders)} 个processed文件夹")
    
    all_results = []
    
    for processed_folder in processed_folders:
        folder_name = os.path.basename(processed_folder)
        print(f"\n处理文件夹: {folder_name}")
        
        # 处理数据
        results = process_processed_folder(processed_folder)
        
        if results:
            all_results.extend(results)
            
    # 在所有文件夹处理完毕后，将结果保存到CSV
    if all_results:
        df_summary = pd.DataFrame(all_results)
        output_csv_path = os.path.join(base_path, 'flow_data_summary.csv')
        df_summary.to_csv(output_csv_path, index=False, encoding='utf-8-sig')
        print(f"\n所有流速数据已汇总并保存到: {output_csv_path}")
    else:
        print("\n没有找到任何有效数据进行汇总。")

if __name__ == "__main__":
    main()
